package com.fulihui.weixinsdk;

import com.fulihui.weixinsdk.http.HttpRequest;
import com.fulihui.weixinsdk.http.HttpRequestType;
import com.fulihui.weixinsdk.http.HttpSelector;
import com.fulihui.weixinsdk.request.WeixinRequest;
import com.fulihui.weixinsdk.result.WeixinResult;
import com.fulihui.weixinsdk.util.WxSDKResultUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * WeixinSDK 实现类 需要被注册到 spring管理
 * Created by LeeSon on 2017/3/30 0030.
 */
public class WeixinSDKImpl implements WeixinSDK {
    private HttpSelector httpSelector;

    public WeixinSDKImpl(HttpSelector httpSelector) {
        this.httpSelector = httpSelector;
    }

    private WeixinSDKImpl() {

    }

    /**
     * @see WeixinSDK#invokeService(WeixinRequest)
     */
    @Override
    public <T extends WeixinResult> T invokeService(WeixinRequest<T> request) {
        if (StringUtils.isBlank(request.service())) {
            throw new IllegalArgumentException("service can not be blank");
        }
        String resp;
        HttpRequest httpRequest = new HttpRequest();
        httpRequest.setUrl(request.service());
        httpRequest.setParams(request.urlParam());
        httpRequest.setData(request.requestData());
        httpRequest.setUrlFoot(request.urlEndStr());
        httpRequest.setFile(request.file());

        switch (request.httpMethod()) {
            case GET:
                resp = httpSelector.client(HttpRequestType.HTTP).doGet(httpRequest);
                break;
            case CERT_SSL_GET:
                resp = httpSelector.client(HttpRequestType.HTTPS).doGet(httpRequest);
                break;
            case POST:
                resp = httpSelector.client(HttpRequestType.HTTP).doPost(httpRequest);
                break;
            case CERT_SSL_POST:
                resp = httpSelector.client(HttpRequestType.HTTPS).doPost(httpRequest);
                break;
            case MULTIPART_POST:
                resp = httpSelector.client(HttpRequestType.MULTIPART_HTTP).doPost(httpRequest);
                break;
            default:
                throw new UnsupportedOperationException(
                        "Unsupported http method:" + request.httpMethod().name());
        }

        T t = request.parseResult(resp);
        WxSDKResultUtil.checkResult(t);

        return t;
    }
}